package com.pirestupppai.imagetool.painttool;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import com.pirestupppai.common.Constant;
import com.pirestupppai.utils.Utils;

import java.util.ArrayList;
import java.util.List;

/**
 *  画笔view
 */

public class PaintView extends View {
    /**
     *   根据原始Bitmap创建mTranslateBitmap，根据mTranslateBitmap初始化mCanvas，然后将原始Bitmap和绘制的Path（考虑图片缩放比例）绘制到mCanvas
     *   得到mTranslateBitmap（包含原始Bitmap和绘制的Path），显示时，将mTranslateBitmap根据缩放matrix绘制到canvas上。
     */
    private Context mContext;
    private int surplusHeight;              // 当前屏幕剩余高度
    private float scaleRate;                // 图片缩放比例
    private Matrix mBackgroundMatrix;       // 图片缩放matrix
    private List<CustomPaintPath> mPathList;
    private CustomPaintPath curCustomPath;  // 当前path
    private Canvas mCanvas;
    private Bitmap mBackgroundBitmap;       // 原始Bitmap
    private Bitmap mTranslateBitmap;        // 绘制原始Bitmap和路径后的Bitmap
    private int mCurrentPaintColor = Color.parseColor("#FC0102");         // 当前画笔的颜色
    private int mCurrentPaintWidth = 20;         // 当前画笔的宽度

    private Paint mClearPaint;        // 用于清屏

    public PaintView(Context context) {
        this(context, null);
        this.mContext = context;
        init();
    }

    public PaintView(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
        this.mContext = context;
        init();
    }

    private void init() {
        surplusHeight = Constant.HEIGHT_OF_SCREEN - Constant.HEIGHT_OF_STATUSBAR
                - Utils.dpToPx(mContext, 64) - Utils.dpToPx(mContext, 85);
        mPathList = new ArrayList<>();

        mClearPaint = new Paint();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // draw背景为白色
        canvas.drawColor(Color.parseColor("#FFFFFF"));

        // 清除mCanvas上的绘制
        mClearPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
        mCanvas.drawPaint(mClearPaint);
        mClearPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC));

        mCanvas.drawBitmap(mBackgroundBitmap, 0, 0, null);
        for (int i = 0; i < mPathList.size(); i++) {
            mCanvas.drawPath(mPathList.get(i).mPath, mPathList.get(i).mPaint);
        }
        canvas.drawBitmap(mTranslateBitmap, mBackgroundMatrix, null);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
        mBackgroundMatrix = new Matrix();
        if (mBackgroundBitmap != null) {
            float surplusRate = (float) Constant.WIDTH_OF_SCREEN / (float)surplusHeight;
            float pictureRate = (float)mBackgroundBitmap.getWidth() / (float)mBackgroundBitmap.getHeight();
            if (pictureRate > surplusRate) {
                scaleRate = (float)Constant.WIDTH_OF_SCREEN / (float)mBackgroundBitmap.getWidth();
                setMeasuredDimension(Constant.WIDTH_OF_SCREEN, Constant.WIDTH_OF_SCREEN * mBackgroundBitmap.getHeight() / mBackgroundBitmap.getWidth());
            } else {
                scaleRate = (float)surplusHeight / (float)mBackgroundBitmap.getHeight();
                setMeasuredDimension(surplusHeight * mBackgroundBitmap.getWidth() / mBackgroundBitmap.getHeight(), surplusHeight);
            }
            mBackgroundMatrix.postScale(scaleRate, scaleRate);
        } else {
            setMeasuredDimension(Constant.WIDTH_OF_SCREEN, surplusHeight);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // 手指滑动的区域是放大或缩小后的图片，考虑缩放比例
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                curCustomPath = new CustomPaintPath();
                mPathList.add(curCustomPath);
                curCustomPath.setmPaintColor(mCurrentPaintColor);
                curCustomPath.setPaintWidth(mCurrentPaintWidth);
                curCustomPath.mPath.moveTo(event.getX() / scaleRate, event.getY() / scaleRate);
                break;
            case MotionEvent.ACTION_MOVE:
                curCustomPath.mPath.lineTo(event.getX() / scaleRate , event.getY() / scaleRate);
                break;
        }
        invalidate();
        return true;
    }

    /**
     * 设置背景Bitmap
     */
    public void setBackgroundBitmap(Bitmap bitmap) {
        this.mBackgroundBitmap = bitmap;
        mTranslateBitmap = Bitmap.createBitmap(mBackgroundBitmap.getWidth(), mBackgroundBitmap.getHeight(), Bitmap.Config.ARGB_8888);
        mCanvas = new Canvas(mTranslateBitmap);
        invalidate();
    }

    /**
     *  获得绘制后的Bitmap
     */
    public Bitmap getmBackgroundBitmap() {
        return mTranslateBitmap;
    }

    /**
     *  撤回上一次画笔
     */
    public void revokePaint() {
        if (mPathList.size() > 0) {
            mPathList.remove(mPathList.size() - 1);
        }
        invalidate();
    }

    /**
     *   设置画笔颜色
     */
    public void setColor(int color) {
        this.mCurrentPaintColor = color;
    }

    /**
     *  设置画笔大小
     */
    public void setSize(int width){
        this.mCurrentPaintWidth = width;
    }
}
